package com.ygqh.baby.service.trustone;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.http.HttpHeaders;
import com.ygqh.baby.exception.CacheException;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.http.YgResponse;
import com.ygqh.baby.service.trustone.model.TokenResult;
import com.ygqh.baby.token.Token;
import com.ygqh.baby.token.TokenCreator;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 */
public class TruStoneTokenCreator extends TokenCreator {

    @Override
    public Token create() throws CacheException {

        TokenResult res;
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("refreshToken", TrustoneConfig.getRefreshToken());
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            YgResponse response = requestExecutor.post(TrustoneConfig.getAccessTokenApi(), headers, JSON.toJSONString(map));

            String string = requestExecutor.toString();

            System.out.println(string);
            System.out.println(response.getAsString());
            res = response.getAsObject(new TypeReference<TokenResult>() {
            });
        } catch (YgHttpException e) {
            e.printStackTrace();
            throw new CacheException(e);
        }
        String tokenStr = res.getToken();
        if (StringUtils.isNotBlank(tokenStr)) {
            return new Token(tokenStr, System.currentTimeMillis() + (4 * 60 * 60 * 1000) - (2 * 60 * 1000), System.currentTimeMillis());
        }
        return null;
    }

    @Override
    public String name() {
        return "trustone_accesstoken_";
    }

    @Override
    public String uniqueid() {
        return TrustoneConfig.getRefreshToken();
    }

}
